<?php if(!class_exists("View", false)) exit("no direct access allowed");?><main class="container mx-auto px-4 pt-24 pb-16 flex">
    <?php include $_view_obj->compile("left_menu.html"); ?>

    <!-- 应用列表 -->
    <section class="mb-10 w-3/4 ml-4 bg-white rounded-xl shadow-sm p-4">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-dark">应用列表</h2>
            <div class="flex items-center space-x-4" id="user-info">
                <button class="btn btn-primary" id="add-app-button">
                    <i class="fa fa-plus"></i>
                    新增应用
                </button>
            </div>
        </div>

        <!--新增滚动容器-->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            ID
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            应用名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            图标
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            应用描述
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            应用入口地址
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            参数
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            状态
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody id="app-list" class="bg-white divide-y divide-gray-200">
                </tbody>
            </table>
        </div>
        <div class="flex justify-center mt-4" id="pagination">
        </div>

    </section>

</main>

<!-- 新增应用弹窗 -->
<div id="add-app-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-3xl w-full">
        <h2 class="text-2xl font-bold mb-6 text-center">新增应用</h2>
        <form id="add-app-form">
            <div class="mb-6">
                <label for="add-app-name" class="block text-sm font-medium text-gray-700">应用名称</label>
                <input type="text" id="add-app-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="add-app-icon" class="block text-sm font-medium text-gray-700">应用图标</label>
                <div class="relative">
                    <input type="text" id="add-app-icon" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm" readonly>
                    <button type="button" class="absolute top-1/2 right-2 transform -translate-y-1/2 btn btn-primary" onclick="openIconPicker('add-app-icon')">选择图标</button>
                </div>
            </div>
            <div class="mb-6">
                <label for="add-category-parent" class="block text-sm font-medium text-gray-700 mb-1">所属分类</label>
                <select id="add-category-parent" class="input-field w-full">
                    <!-- 分类选项将通过 JavaScript 动态添加 -->
                </select>
            </div>
            <div class="mb-6">
                <label for="add-app-desc" class="block text-sm font-medium text-gray-700">应用描述</label>
                <textarea id="add-app-desc" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"></textarea>
            </div>
            <div class="mb-6">
                <label for="add-app-url" class="block text-sm font-medium text-gray-700">应用入口地址</label>
                <input type="text" id="add-app-url" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="add-app-params" class="block text-sm font-medium text-gray-700">参数</label>
                <input type="text" id="add-app-params" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="add-app-status" class="block text-sm font-medium text-gray-700">状态</label>
                <select id="add-app-status" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
                    <option value="1">正常</option>
                    <option value="0">下线</option>
                </select>
            </div>
            <div class="flex justify-end">
                <button type="button" class="btn btn-secondary mr-2" onclick="closeAddAppModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 编辑应用弹窗 -->
<div id="edit-app-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-3xl w-full">
        <h2 class="text-2xl font-bold mb-6 text-center">编辑应用</h2>
        <form id="edit-app-form">
            <input type="hidden" id="edit-app-id">
            <div class="mb-6">
                <label for="edit-app-name" class="block text-sm font-medium text-gray-700">应用名称</label>
                <input type="text" id="edit-app-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="edit-app-icon" class="block text-sm font-medium text-gray-700">应用图标</label>
                <div class="relative">
                    <input type="text" id="edit-app-icon" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm" readonly>
                    <button type="button" class="absolute top-1/2 right-2 transform -translate-y-1/2 btn btn-primary" onclick="openIconPicker('edit-app-icon')">选择图标</button>
                </div>
            </div>
            <div class="mb-6">
                <label for="edit-category-parent" class="block text-sm font-medium text-gray-700 mb-1">所属分类</label>
                <select id="edit-category-parent" class="input-field w-full">
                    <!-- 分类选项将通过 JavaScript 动态添加 -->
                </select>
            </div>
            <div class="mb-6">
                <label for="edit-app-desc" class="block text-sm font-medium text-gray-700">应用描述</label>
                <textarea id="edit-app-desc" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"></textarea>
            </div>
            <div class="mb-6">
                <label for="edit-app-url" class="block text-sm font-medium text-gray-700">应用入口地址</label>
                <input type="text" id="edit-app-url" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="edit-app-params" class="block text-sm font-medium text-gray-700">参数</label>
                <input type="text" id="edit-app-params" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="edit-app-status" class="block text-sm font-medium text-gray-700">状态</label>
                <select id="edit-app-status" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
                    <option value="1">正常</option>
                    <option value="0">下线</option>
                </select>
            </div>
            <div class="flex justify-end">
                <button type="button" class="btn btn-secondary mr-2" onclick="closeEditAppModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 图标选择器弹窗 -->
<div id="icon-picker-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-4xl w-full">
        <h2 class="text-2xl font-bold mb-6 text-center">选择图标</h2>
        <!-- 添加样式让图标列表可以滚动 -->
        <div id="icon-list" class="grid grid-cols-6 gap-4 max-h-96 overflow-y-auto p-4 border rounded-md">
            <!-- 这里会动态插入图标 -->
        </div>
        <div class="flex justify-end mt-6">
            <button type="button" class="btn btn-secondary" onclick="closeIconPicker()">关闭</button>
        </div>
    </div>
</div>

<!-- 模块配置弹窗 -->
<!-- 模块配置弹窗 -->
<div id="module-config-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-4xl w-full max-h-[90vh] flex flex-col">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-2xl font-bold">模块配置</h2>
            <button type="button" class="text-gray-500 hover:text-gray-700" onclick="closeModuleConfigModal()">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>
        <!-- 模块列表 - 添加最大高度和滚动条 -->
        <div class="overflow-x-auto overflow-y-auto flex-grow max-h-[calc(90vh-200px)] mb-4">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50 sticky top-0">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            模块 ID
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            模块名称
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody id="module-list" class="bg-white divide-y divide-gray-200">
                </tbody>
            </table>
        </div>
        <!-- 新增模块按钮 -->
        <div class="flex justify-end mb-4">
            <button class="btn btn-primary" id="add-module-button">
                <i class="fa fa-plus"></i>
                新增模块
            </button>
        </div>
    </div>
</div>

<!-- 新增模块弹窗 -->
<div id="add-module-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden bg-gray-500 bg-opacity-75">
    <div class="bg-white p-8 rounded-xl shadow-lg max-w-3xl w-full">
        <h2 class="text-2xl font-bold mb-6 text-center">新增模块</h2>
        <form id="add-module-form">
            <input type="hidden" id="add-module-app-id">
            <div class="grid grid-cols-2 gap-6 mb-6">
                <div>
                    <label for="add-module-type" class="block text-sm font-medium text-gray-700">模块类型</label>
                    <select id="add-module-type" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
                        <option value="1">页面级</option>
                        <option value="2" selected>接口级</option>
                    </select>
                </div>
                <div>
                    <label for="add-module-group" class="block text-sm font-medium text-gray-700">组 ID</label>
                    <input type="number" id="add-module-group" value="0" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
                </div>
            </div>
            <div class="grid grid-cols-2 gap-6 mb-6">
                <div>
                    <label for="add-module-name" class="block text-sm font-medium text-gray-700">模块名称</label>
                    <input type="text" id="add-module-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm" required>
                </div>
                <div>
                    <label for="add-module-method-name" class="block text-sm font-medium text-gray-700">方法名称</label>
                    <input type="text" id="add-module-method-name" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm" required>
                </div>
            </div>
            <div class="grid grid-cols-2 gap-6 mb-6">
                <div>
                    <label for="add-module-controller" class="block text-sm font-medium text-gray-700">控制器</label>
                    <input type="text" id="add-module-controller" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm" required>
                </div>
                <div>
                    <label for="add-module-function" class="block text-sm font-medium text-gray-700">函数</label>
                    <input type="text" id="add-module-function" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm" required>
                </div>
            </div>
            <div class="mb-6">
                <label for="add-module-url" class="block text-sm font-medium text-gray-700">页面 URL</label>
                <input type="text" id="add-module-url" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="mb-6">
                <label for="add-module-title" class="block text-sm font-medium text-gray-700">标题</label>
                <input type="text" id="add-module-title" class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
            </div>
            <div class="flex justify-end">
                <button type="button" class="btn btn-secondary mr-2" onclick="closeAddModuleModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    const itemsPerPage = 5;
    let currentPage = 1;
    let totalUsers = 0;
    let targetInputId = '';

    function buildDeptTree(depts) {
        // 初始化树结构和ID映射
        const tree = {};
        const idMap = {};

        // 第一步：将所有部门放入ID映射表
        depts.forEach(dept => {
            idMap[dept.category_id] = { ...dept, children: [] };
        });
        
        // 第二步：构建树结构
        depts.forEach(dept => {
            // 处理特殊顶级标识（如"-1"）
            if (dept.pid === "-1" || dept.pid === null || dept.pid === "") {
                tree[dept.category_id] = idMap[dept.category_id];
            } else {
                // 处理子节点（注意pid是字符串类型）
                if (idMap[dept.pid]) {
                    idMap[dept.pid].children.push(idMap[dept.category_id]);
                }
            }
        });

        return tree;
    }

    // 递归生成树形选项（优化子树构建逻辑）
    function generateTreeOptions(tree, level = 0) {
        let options = '';
        for (const id in tree) {
            const dept = tree[id];
            const indent = '&nbsp;&nbsp;&nbsp;&nbsp;'.repeat(level);
            options += `<option value="${dept.category_id}">${indent}${dept.category_name}</option>`;
            
            // 直接使用children数组，无需重新调用buildDeptTree
            if (dept.children && dept.children.length > 0) {
                options += generateTreeOptions(dept.children, level + 1);
            }
        }
        return options;
    }

    // 获取分类列表
    function getCategoryList() {
        const url = '<?php echo url(array('c'=>"system", 'a'=>"GetCategory", ));?>';
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const depts = response.data;
                const addDeptSelect = $('#add-category-parent');
                const editDeptSelect = $('#edit-category-parent');
                addDeptSelect.empty();
                editDeptSelect.empty();
                // console.log(depts)
                // 使用接口返回的数据构建树并生成选项
                const deptTree = buildDeptTree(depts);
                const optionsHtml = generateTreeOptions(deptTree);

                // 添加调试信息
                // console.log('生成的选项:', options);

                addDeptSelect.append(optionsHtml);
                editDeptSelect.append(optionsHtml);
            },
            error: function (error) {
                console.error('获取部门列表失败:', error);
            }
        });
    }
    // 配置模块函数
    function configModule(appId) {
        const url = '<?php echo url(array('c'=>"system", 'a'=>"AppsPrivIndex", ));?>?id=' + appId;
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                console.log(response);
                const modules = response.data.apps;
                const moduleList = $('#module-list');
                moduleList.empty();

                modules.forEach(module => {
                    const parentRow = $('<tr>');
                    parentRow.html(`
                        <td class="px-6 py-4 whitespace-nowrap">${module.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${module.moduleName} - ${module.methodName}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button class="btn btn-danger" onclick="deleteModule(${module.id})">删除</button>
                        </td>
                    `);
                    moduleList.append(parentRow);

                    if (module.childs && module.childs.length > 0) {
                        module.childs.forEach(child => {
                            const childRow = $('<tr>');
                            childRow.html(`
                                <td class="px-6 py-4 whitespace-nowrap pl-12">${child.id}</td>
                                <td class="px-6 py-4 whitespace-nowrap pl-12">${child.moduleName} - ${child.methodName}</td>
                                <td class="px-6 py-4 whitespace-nowrap pl-12">
                                    <button class="btn btn-danger" onclick="deleteModule(${child.id})">删除</button>
                                </td>
                            `);
                            moduleList.append(childRow);
                        });
                    }
                });

                $('#edit-app-id').val(appId);
                $('#module-config-modal').removeClass('hidden');
            },
            error: function (error) {
                console.error('请求模块数据失败:', error);
                alert('获取模块数据失败，请稍后重试');
            }
        });
    }

    // 关闭模块配置弹窗
    function closeModuleConfigModal() {
        $('#module-config-modal').addClass('hidden');
    }

    // 删除模块函数
    function deleteModule(moduleId) {
        if (confirm('确定要删除该模块吗？')) {
            const url = '<?php echo url(array('c'=>"system", 'a'=>"deleteModuleById", ));?>?moduleId=' + moduleId;
            $.ajax({
                url: url,
                method: 'GET',
                dataType: 'json',
                success: function (response) {
                    if (response.status / 1 === 0) {
                        alert('模块删除成功');
                        // 重新加载模块列表
                        const appId = $('#edit-app-id').val();
                        configModule(appId);
                    } else {
                        alert('模块删除失败: ' + response.msg);
                    }
                },
                error: function (error) {
                    console.error('请求删除模块数据失败:', error);
                    alert('删除模块失败，请稍后重试');
                }
            });
        }
    }

    // 新增模块按钮点击事件
    $('#add-module-button').on('click', function () {
        const appId = $('#edit-app-id').val();
        if (!appId) {
            alert('请先选择应用');
            return;
        }
        
        $('#add-module-app-id').val(appId);
        $('#add-module-modal').removeClass('hidden');
    });

    // 关闭新增模块弹窗
    function closeAddModuleModal() {
        $('#add-module-modal').addClass('hidden');
        $('#add-module-form')[0].reset();
    }

    // 新增模块表单提交事件
    $('#add-module-form').on('submit', function (e) {
        e.preventDefault();
        
        const appId = $('#add-module-app-id').val();
        const type = $('#add-module-type').val();
        const module = $('#add-module-controller').val();
        const method = $('#add-module-function').val();
        const url = $('#add-module-url').val();
        const title = $('#add-module-title').val();
        const moduleName = $('#add-module-name').val();
        const methodName = $('#add-module-method-name').val();
        const group = $('#add-module-group').val();
        const category = $('#add-category-parent').val();

        
        $.ajax({
            url: '<?php echo url(array('c'=>"system", 'a'=>"GroupprivAdd", ));?>',
            method: 'POST',
            data: {
                appid: appId,
                type: type,
                module: module,
                method: method,
                url: url,
                title: title,
                moduleName: moduleName,
                methodName: methodName,
                group: group
            },
            dataType: 'json',
            success: function (response) {
                if (response.code / 1 === 1) {
                    alert('模块添加成功');
                    closeAddModuleModal();
                    // 重新加载模块列表
                    configModule(appId);
                } else {
                    alert('模块添加失败: ' + response.message);
                }
            },
            error: function (error) {
                console.error('请求添加模块数据失败:', error);
                alert('添加模块失败，请稍后重试');
            }
        });
    });

    // 应用列表
    function displayApps() {
        const url = '<?php echo url(array('c'=>"system", 'a'=>"AppsIndexList", ));?>?start=' + currentPage + '&limit=' + itemsPerPage;

        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const users = response.data.list;
                totalUsers = response.data.pager.total_count;
                console.log(totalUsers);

                const userList = $('#app-list');
                userList.empty();

                users.forEach(app => {
                    const row = $('<tr>');
                    const maxLength = 20; // 最大显示长度
                    const displayUrl = app.appUrl.length > maxLength ? app.appUrl.slice(0, maxLength) + '...' : app.appUrl;
                    row.html(`
                        <td class="px-6 py-4 whitespace-nowrap">${app.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${app.appName}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <i class="fa ${app.appImg} text-xl animate-pulse"></i>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">${app.appDesc}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span title="${app.appUrl}">${displayUrl}</span>
                            <button class="btn btn-secondary ml-2" onclick="copyUrl('${app.appUrl}')">复制</button>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">${app.appParams}</td>
                        <td class="px-6 py-4 whitespace-nowrap ${app.appStatus / 1 === 1 ? '' : 'text-danger'} ">
                            ${app.appStatus / 1 === 1 ? '正常' : '下线'}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button class="btn btn-info mr-2" onclick="configModule(${app.id})">配置模块</button>
                            <button class="btn btn-warning mr-2" onclick="editApp(${app.id})">编辑</button>
                            <button class="btn btn-danger" onclick="deleteUser(${app.id})">删除</button>
                        </td>
                    `);
                    userList.append(row);
                });

                displayPagination();
            },
            error: function (error) {
                console.error('请求数据失败:', error);
            }
        });
    }

    // 复制URL函数
    function copyUrl(url) {
        const tempInput = document.createElement('input');
        tempInput.value = url;
        document.body.appendChild(tempInput);
        tempInput.select();
        document.execCommand('copy');
        document.body.removeChild(tempInput);
        alert('URL已复制到剪贴板');
    }

    // 编辑应用函数
    function editApp(id) {
        const url = '<?php echo url(array('c'=>"system", 'a'=>"getAppById", ));?>?id=' + id;
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const app = response.data;
                $('#edit-app-id').val(app.id);
                $('#edit-app-name').val(app.appName);
                $('#edit-app-icon').val(app.appImg);
                $('#edit-app-desc').val(app.appDesc);
                $('#edit-app-url').val(app.appUrl);
                $('#edit-app-params').val(app.appParams);
                $('#edit-app-status').val(app.appStatus);
                $('#edit-category-parent').val(app.categoryId);                
                $('#edit-app-modal').removeClass('hidden');
                getCategoryList();
            },
            error: function (error) {
                console.error('请求编辑数据失败:', error);
                alert('获取编辑数据失败，请稍后重试');
            }
        });
    }

    // 显示分页导航
    function displayPagination() {
        const totalPages = Math.ceil(totalUsers / itemsPerPage);
        const pagination = $('#pagination');
        pagination.empty();

        const maxVisiblePages = 5; // 最大可见页码数
        const startPage = Math.max(currentPage - Math.floor(maxVisiblePages / 2), 1);
        const endPage = Math.min(startPage + maxVisiblePages - 1, totalPages);

        // 上一页按钮
        if (currentPage > 1) {
            const prevButton = $('<button>');
            prevButton.text('上一页');
            prevButton.addClass('px-3 py-1 mx-1 border rounded');
            prevButton.on('click', function () {
                currentPage--;
                displayApps();
            });
            pagination.append(prevButton);
        }

        // 页码按钮
        for (let i = startPage; i <= endPage; i++) {
            const button = $('<button>');
            button.text(i);
            button.addClass('px-3 py-1 mx-1 border rounded');
            if (i === currentPage) {
                button.addClass('bg-primary text-white');
            }
            button.on('click', function () {
                currentPage = i;
                displayApps();
            });
            pagination.append(button);
        }

        // 下一页按钮
        if (currentPage < totalPages) {
            const nextButton = $('<button>');
            nextButton.text('下一页');
            nextButton.addClass('px-3 py-1 mx-1 border rounded');
            nextButton.on('click', function () {
                currentPage++;
                displayApps();
            });
            pagination.append(nextButton);
        }
    }

    // 打开新增应用弹窗
    $('#add-app-button').on('click', function () {
        $('#add-app-modal').removeClass('hidden');
        getCategoryList()
    });

    // 关闭新增应用弹窗
    function closeAddAppModal() {
        $('#add-app-modal').addClass('hidden');
        $('#add-app-form')[0].reset();
    }

    // 关闭编辑应用弹窗
    function closeEditAppModal() {
        $('#edit-app-modal').addClass('hidden');
        $('#edit-app-form')[0].reset();
    }

    // 打开图标选择器
    function openIconPicker(inputId) {
        targetInputId = inputId;
        $('#icon-picker-modal').removeClass('hidden');
        loadIcons();
    }

    // 关闭图标选择器
    function closeIconPicker() {
        $('#icon-picker-modal').addClass('hidden');
    }

    // 加载图标
    function loadIcons() {
        const iconList = $('#icon-list');
        iconList.empty();

        // 这里可以根据需要添加更多的图标类名
        const icons = [
            // 通用图标
            'fa-home', 'fa-user', 'fa-envelope', 'fa-cog', 'fa-shopping-cart',
            'fa-bell', 'fa-star', 'fa-heart', 'fa-trash', 'fa-search',
            'fa-book', 'fa-map-marker', 'fa-phone', 'fa-lock', 'fa-unlock',
            'fa-clock', 'fa-calendar', 'fa-camera', 'fa-video', 'fa-music',
            'fa-comment', 'fa-comments', 'fa-thumbs-up', 'fa-thumbs-down', 'fa-share',
            'fa-print', 'fa-download', 'fa-upload', 'fa-link', 'fa-chain-broken',
            'fa-tag', 'fa-tags', 'fa-globe', 'fa-language', 'fa-money',
            'fa-gift', 'fa-trophy', 'fa-briefcase', 'fa-file', 'fa-file-text',
            'fa-picture-o', 'fa-video-camera', 'fa-microphone', 'fa-volume-up', 'fa-volume-off',
            'fa-headphones', 'fa-cut', 'fa-copy', 'fa-paste', 'fa-undo',
            'fa-repeat', 'fa-refresh', 'fa-play', 'fa-pause', 'fa-stop',
            'fa-forward', 'fa-backward', 'fa-fast-forward', 'fa-fast-backward', 'fa-step-forward',
            'fa-step-backward', 'fa-eject', 'fa-plus', 'fa-minus', 'fa-times',
            'fa-check', 'fa-question', 'fa-info', 'fa-exclamation', 'fa-exclamation-triangle',
            'fa-ban', 'fa-eye', 'fa-eye-slash', 'fa-pencil', 'fa-pencil-square-o',
            'fa-edit', 'fa-trash-o', 'fa-save', 'fa-floppy-o', 'fa-external-link',
            'fa-sign-in', 'fa-sign-out', 'fa-user-plus', 'fa-user-times', 'fa-users',
            'fa-group', 'fa-child', 'fa-male', 'fa-female', 'fa-mars',
            'fa-venus', 'fa-transgender', 'fa-mars-double', 'fa-venus-double', 'fa-mars-stroke',
            'fa-mars-stroke-v', 'fa-mars-stroke-h', 'fa-venus-mars', 'fa-neuter', 'fa-facebook',
            'fa-twitter', 'fa-instagram', 'fa-linkedin', 'fa-youtube', 'fa-pinterest',
            'fa-github', 'fa-bitbucket', 'fa-stack-overflow', 'fa-reddit', 'fa-tumblr',
            'fa-flickr', 'fa-dribbble', 'fa-behance', 'fa-medium', 'fa-quora',
            'fa-snapchat', 'fa-whatsapp', 'fa-telegram', 'fa-skype', 'fa-slack',
            'fa-vk', 'fa-weibo', 'fa-renren', 'fa-qq', 'fa-weixin',
            'fa-alipay', 'fa-cc-visa', 'fa-cc-mastercard', 'fa-cc-amex', 'fa-cc-discover',
            'fa-cc-paypal', 'fa-cc-stripe', 'fa-btc', 'fa-eth', 'fa-usd',
            'fa-eur', 'fa-gbp', 'fa-jpy', 'fa-cny', 'fa-rub',
            'fa-bitcoin', 'fa-ether', 'fa-dollar', 'fa-euro', 'fa-pound',
            'fa-yen', 'fa-ruble', 'fa-try', 'fa-rupee', 'fa-won',
            'fa-ils', 'fa-krw', 'fa-brl', 'fa-cad', 'fa-aud',
            'fa-chf', 'fa-dkk', 'fa-hkd', 'fa-nok', 'fa-nzd',
            'fa-pln', 'fa-sek', 'fa-sgd', 'fa-thb', 'fa-twd',
            'fa-angle-up', 'fa-angle-down', 'fa-angle-left', 'fa-angle-right',
            'fa-arrow-up', 'fa-arrow-down', 'fa-arrow-left', 'fa-arrow-right',
            'fa-caret-up', 'fa-caret-down', 'fa-caret-left', 'fa-caret-right',
            'fa-sort', 'fa-sort-up', 'fa-sort-down', 'fa-filter', 'fa-list',
            'fa-list-ul', 'fa-list-ol', 'fa-bars', 'fa-navicon', 'fa-reorder',
            'fa-th', 'fa-th-large', 'fa-th-list', 'fa-table', 'fa-columns',
            'fa-align-left', 'fa-align-center', 'fa-align-right', 'fa-align-justify',
            'fa-indent', 'fa-outdent', 'fa-bold', 'fa-italic', 'fa-underline',
            'fa-strikethrough', 'fa-superscript', 'fa-subscript', 'fa-eraser', 'fa-clipboard',
            'fa-anchor', 'fa-archive', 'fa-at', 'fa-asterisk', 'fa-automobile',
            'fa-bus', 'fa-train', 'fa-ship', 'fa-plane', 'fa-rocket',
            'fa-space-shuttle', 'fa-wheelchair', 'fa-blind', 'fa-deaf', 'fa-glasses',
            'fa-umbrella', 'fa-fire', 'fa-fire-extinguisher', 'fa-bug', 'fa-bolt',
            'fa-paper-plane', 'fa-send', 'fa-paperclip', 'fa-folder', 'fa-folder-open',
            'fa-inbox', 'fa-outbox', 'fa-exchange', 'fa-arrows', 'fa-arrows-h',
            'fa-arrows-v', 'fa-expand', 'fa-compress', 'fa-maximize', 'fa-minimize',
            'fa-life-ring', 'fa-circle', 'fa-circle-o', 'fa-dot-circle-o', 'fa-check-circle',
            'fa-times-circle', 'fa-exclamation-circle', 'fa-info-circle', 'fa-question-circle',
            'fa-ban-circle', 'fa-circle-thin', 'fa-circle-notch', 'fa-spinner', 'fa-refresh',
            'fa-cog', 'fa-cogs', 'fa-wrench', 'fa-screwdriver', 'fa-hammer',
            'fa-bullhorn', 'fa-bullseye', 'fa-crosshairs', 'fa-certificate', 'fa-ticket',
            'fa-credit-card', 'fa-qrcode', 'fa-barcode', 'fa-tasks', 'fa-filter',
            'fa-list-alt', 'fa-building', 'fa-hospital', 'fa-bank', 'fa-university',
            'fa-school', 'fa-library', 'fa-museum', 'fa-grocery-store', 'fa-restaurant',
            'fa-coffee', 'fa-beer', 'fa-wine-glass', 'fa-cutlery', 'fa-birthday-cake',
            'fa-cookie', 'fa-apple', 'fa-lemon', 'fa-carrot', 'fa-hamburger',
            'fa-pizza-slice', 'fa-ice-cream', 'fa-drumstick-bite', 'fa-fish', 'fa-paw',
            'fa-cat', 'fa-dog', 'fa-bird', 'fa-horse', 'fa-sheep',
            'fa-cow', 'fa-piggy-bank', 'fa-gamepad', 'fa-headset', 'fa-keyboard',
            'fa-mouse-pointer', 'fa-desktop', 'fa-laptop', 'fa-tablet', 'fa-mobile',
            'fa-mobile-alt', 'fa-print', 'fa-fax', 'fa-envelope-open', 'fa-envelope-open-text',
            'fa-envelope-square', 'fa-inbox', 'fa-outbox', 'fa-file-alt', 'fa-file-archive',
            'fa-file-audio', 'fa-file-code', 'fa-file-excel', 'fa-file-image', 'fa-file-pdf',
            'fa-file-powerpoint', 'fa-file-video', 'fa-file-word', 'fa-folder', 'fa-folder-open',
            'fa-folder-plus', 'fa-folder-minus', 'fa-hdd', 'fa-memory', 'fa-sd-card',
            'fa-usb', 'fa-wifi', 'fa-bluetooth', 'fa-bluetooth-b', 'fa-signal',
            'fa-battery-full', 'fa-battery-three-quarters', 'fa-battery-half', 'fa-battery-quarter', 'fa-battery-empty',
            'fa-plug', 'fa-lightbulb', 'fa-fire', 'fa-fire-extinguisher', 'fa-bug',
            'fa-bolt', 'fa-paper-plane', 'fa-send', 'fa-paperclip', 'fa-folder',
            'fa-folder-open', 'fa-inbox', 'fa-outbox', 'fa-exchange', 'fa-arrows',
            'fa-arrows-h', 'fa-arrows-v', 'fa-expand', 'fa-compress', 'fa-maximize',
            'fa-minimize', 'fa-life-ring', 'fa-circle', 'fa-circle-o', 'fa-dot-circle-o',
            'fa-check-circle', 'fa-times-circle', 'fa-exclamation-circle', 'fa-info-circle', 'fa-question-circle',
            'fa-ban-circle', 'fa-circle-thin', 'fa-circle-notch', 'fa-spinner', 'fa-refresh',
            'fa-cog', 'fa-cogs', 'fa-wrench', 'fa-screwdriver', 'fa-hammer'
        ];

        icons.forEach(icon => {
            const iconElement = $('<div>');
            iconElement.html(`<i class="fa ${icon} text-2xl"></i>`);
            iconElement.addClass('cursor-pointer hover:text-primary p-2 rounded-md');
            iconElement.on('click', function () {
                $(`#${targetInputId}`).val(icon);
                closeIconPicker();
            });
            iconList.append(iconElement);
        });
    }

    // 删除应用函数
    function deleteUser(id) {
        if (confirm('确定要删除该应用吗？')) {
            const url = '<?php echo url(array('c'=>"system", 'a'=>"deleteAppById", ));?>?id=' + id;
            $.ajax({
                url: url,
                method: 'GET',
                dataType: 'json',
                success: function (response) {
                    if (response.status/1 === 0) {
                        alert('应用删除成功');
                        displayApps();
                    } else {
                        alert('应用删除失败: ' + response.message);
                    }
                },
                error: function (error) {
                    console.error('请求删除数据失败:', error);
                    alert('删除应用失败，请稍后重试');
                }
            });
        }
    }

    // 新增应用表单提交事件
    $('#add-app-form').on('submit', function (e) {
        e.preventDefault();
        const appName = $('#add-app-name').val();
        const appIcon = $('#add-app-icon').val();
        const appDesc = $('#add-app-desc').val();
        const appUrl = $('#add-app-url').val();
        const appParams = $('#add-app-params').val();
        const appStatus = $('#add-app-status').val();
        const category = $('#add-category-parent').val();

        const url = '<?php echo url(array('c'=>"system", 'a'=>"addApp", ));?>';
        $.ajax({
            url: url,
            method: 'POST',
            data: {
                appName: appName,
                appIcon: appIcon,
                appDesc: appDesc,
                appUrl: appUrl,
                appParams: appParams,
                appStatus: appStatus,
                categoryId :category
            },
            dataType: 'json',
            success: function (response) {
                if (response.status/1 === 0) {
                    alert('应用添加成功');
                    closeAddAppModal();
                    displayApps();
                } else {
                    alert('应用添加失败: ' + response.message);
                }
            },
            error: function (error) {
                console.error('请求添加数据失败:', error);
                alert('添加应用失败，请稍后重试');
            }
        });
    });

    // 编辑应用表单提交事件
    $('#edit-app-form').on('submit', function (e) {
        e.preventDefault();
        const appId = $('#edit-app-id').val();
        const appName = $('#edit-app-name').val();
        const appIcon = $('#edit-app-icon').val();
        const appDesc = $('#edit-app-desc').val();
        const appUrl = $('#edit-app-url').val();
        const appParams = $('#edit-app-params').val();
        const appStatus = $('#edit-app-status').val();
        const category = $('#edit-category-parent').val();

        const url = '<?php echo url(array('c'=>"system", 'a'=>"updateApp", ));?>';
        $.ajax({
            url: url,
            method: 'POST',
            data: {
                id: appId,
                appName: appName,
                appIcon: appIcon,
                appDesc: appDesc,
                appUrl: appUrl,
                appParams: appParams,
                appStatus: appStatus,
                categoryId:category
            },
            dataType: 'json',
            success: function (response) {
                if (response.status/1 == 0) {
                    alert('应用编辑成功');
                    closeEditAppModal();
                    displayApps();
                } else {
                    alert('应用编辑失败: ' + response.message);
                }
            },
            error: function (error) {
                console.error('请求编辑数据失败:', error);
                alert('编辑应用失败，请稍后重试');
            }
        });
    });

    displayApps();
</script>